package com.xindao.photonics.fragments.manager;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.protocol.MoccaApi;

public abstract class BaseFragment extends Fragment implements ISwitchFragment {
    final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share");
    /** 头部bar */
    protected View mTopTabBarView;
    /** 加载中 */
    private View mLoadingView;
    /** 重试 */
    private View mRetryView;
    private boolean isDataArrived;
    private MoccaApi mMoccaApi;

    private Bundle mBundle;

    /** 播放加载时动画 */
    protected FrameLayout loading;
    protected AnimationDrawable animation;
    protected View load_fail;


    protected View fragment;

    private ImageView imageView;
    protected Activity mActivity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMoccaApi = HappyPetApplication.get().getMoccaApi();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mActivity = getActivity();
        mTopTabBarView = getActivity().getWindow().getDecorView().findViewById(R.id.top_bar);
        mLoadingView = getView().findViewById(R.id.loading);
        mRetryView = getView().findViewById(R.id.retry);
        ll_load_fail = getView().findViewById(R.id.ll_load_fail);
        setTabBar();
        initTabBarViews();
        initLoading();
        initViews(getView());
        initEvents();
        initEvents(getView());
        onLoadData();

        hideKeyBoard();
    }

    protected void initEvents(View view) {

    }

    private void initLoading() {
        // load_fail = getView().findViewById(R.id.ll_load_fail);
        // load_fail.setVisibility(View.GONE);
        fragment = getView().findViewById(R.id.loading);
        imageView = (ImageView) getView().findViewById(R.id.imageView);
        if (imageView != null) {
            imageView.setBackgroundResource(R.anim.alertdialog_animation);
            animation = (AnimationDrawable) imageView.getBackground();
            animation.setOneShot(false);
            animation.start();
        }

    }

    protected void initEvents() {}

    /** 加载数据 */
    protected void onLoadData() {
        if (null != imageView && !isDataArrived) {
            animation.start();
            imageView.setVisibility(View.VISIBLE);
        }
        if (null != mRetryView) {
            imageView.setVisibility(View.GONE);
            imageView.setOnClickListener(mBaseOnClickListener);
        }
    }

    protected void initViews(View view) {}

    protected final MoccaApi getMoccaApi() {
        return mMoccaApi;
    }

    private void initTabBarViews() {
        if (mTopTabBarView == null) {
            return;
        }
        View back = mTopTabBarView.findViewById(R.id.back);
        if (back != null) {
            if (showBackButton()) {
                back.setVisibility(View.VISIBLE);
                back.setOnClickListener(mBaseOnClickListener);
            } else {
                back.setVisibility(View.INVISIBLE);
            }
        }
        TextView name = (TextView) mTopTabBarView.findViewById(R.id.title);
        if (name != null && !TextUtils.isEmpty(getTitleName())) {
            name.setText(getTitleName());
        }
        TextView right = (TextView) mTopTabBarView.findViewById(R.id.right);
        if (right != null) {
            if (!TextUtils.isEmpty(getRightName())) {
                right.setText(getRightName());
            }
            if (showRightView()) {
                right.setVisibility(View.VISIBLE);
            } else {
                right.setVisibility(View.GONE);
            }
            setRightViewListener(right);
        }

        ImageView rightIcon = (ImageView) mTopTabBarView.findViewById(R.id.right_icon);

        if (rightIcon != null) {
            if (getRightDrawable() != 0) {
                rightIcon.setVisibility(View.VISIBLE);
                rightIcon.setImageResource(getRightDrawable());
            }
            setRightViewListener(rightIcon);
        }

    }

    protected String getTitleName() {
        return null;
    }

    protected String getRightName() {
        return null;
    }

    protected int getRightDrawable() {
        return 0;
    }

    protected void setTopBarRightButtonDrawable(int resId) {
        ImageView rightIcon = (ImageView) mTopTabBarView.findViewById(R.id.right_icon);
        if (rightIcon != null) {
            if (getRightDrawable() != 0) {
                rightIcon.setVisibility(View.VISIBLE);
                rightIcon.setImageResource(resId);
            }
        }
    }

    protected final void setTabTitle(String title) {
        TextView name = (TextView) mTopTabBarView.findViewById(R.id.title);
        if (name != null) {
            name.setText(title);
        }
    }

    protected final View getRightView() {
        return mTopTabBarView.findViewById(R.id.right);
    }

    /** 给导航右侧按钮添加事件 */
    /*
     * protected final void addTopBarRightViewListener(OnClickListener listener) { TextView right =
     * (TextView) mTopTabBarView.findViewById(R.id.right); if (right != null) {
     * right.setOnClickListener(listener); } }
     */

    protected void setRightViewListener(View view) {

    }

    private final View.OnClickListener mBaseOnClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.back:
                    hideKeyBoard();
                    if (!backFragment()) {
                        getActivity().finish();
                    }
                    break;
                case R.id.retry:
                    onLoadData();
                    break;
                default:
                    break;
            }
        }
    };
    private View ll_load_fail;

    /**
     * 是否进行一些操作
     * 
     * @return true 不立即返回
     */
    public boolean handleOptions() {
        return false;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            setTabBar();
            initTabBarViews();
            hideKeyBoard();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    private void setTabBar() {
        if (null != mTopTabBarView) {
            if (showTopTabBar()) {
                mTopTabBarView.setVisibility(View.VISIBLE);
            } else {
                mTopTabBarView.setVisibility(View.GONE);
            }
        }
    }

    protected final void onDataArrived(boolean isArrived) {
        if (!isArrived) {
            isDataArrived = false;
            if (null != imageView) {
                if (animation != null) {
                    animation.stop();
                }
                imageView.setVisibility(View.GONE);
            }
            if (null != mRetryView) {
                mRetryView.setVisibility(View.GONE);
            } else if (ll_load_fail != null) {
                ll_load_fail.setVisibility(View.VISIBLE);
                ll_load_fail.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        ll_load_fail.setVisibility(View.GONE);
                        onLoadData();
                    }
                });
            }

            // onDataArrived(obj);
        } else {
            isDataArrived = true;
            if (null != imageView) {
                if (animation != null) {
                    animation.stop();
                }
                imageView.setVisibility(View.GONE);

            }
            if (null != mRetryView) {
                if (animation != null) {
                    animation.stop();
                }
                mRetryView.setVisibility(View.GONE);
            }
            if (fragment != null) {
                fragment.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 数据到达
     * 
     * @param obj
     */
    /*
     * protected void onDataArrived(Object obj) {
     * 
     * }
     */

    /**
     * 是否显示底部tab栏，默认不显示
     * 
     * @return
     */
    protected boolean showBottomTabBar() {
        return false;
    }

    /**
     * 是否显示底部tab栏，默认显示
     * 
     * @return
     */
    protected boolean showTopTabBar() {
        return true;
    }

    /**
     * 是否显示顶部返回按钮，默认显示
     * 
     * @return
     */
    protected boolean showBackButton() {
        return true;
    }

    /**
     * 是否显示顶部分享，默认显示
     * 
     * @return
     */
    protected boolean showRightView() {
        return true;
    }

    protected void onFragmentResult(Bundle bundle) {}

    /** 隐藏键盘 */
    protected final void hideKeyBoard() {
        InputMethodManager inputManager =
                (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(getView().getWindowToken(), 0);
    }

    protected final void showKeyBoard() {
        InputMethodManager inputManager =
                (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInputFromInputMethod(getView().getWindowToken(), 0);
    }

    @Override
    public final void startTabFragment(Class<? extends BaseFragment> clzz) {
        ((ISwitchFragment) getActivity()).startTabFragment(clzz);
    }

    @Override
    public final void startFragment(BaseFragment fragment) {
        ((ISwitchFragment) getActivity()).startFragment(fragment);
    }

    @Override
    public final void startFragment(BaseFragment fragment, Bundle bundle) {
        ((ISwitchFragment) getActivity()).startFragment(fragment, bundle);
    }

    @Override
    public final boolean backFragment() {
        return ((ISwitchFragment) getActivity()).backFragment();
    }

    /*
     * @Override public final boolean backFragment() { return backFragment(mBundle); }
     */

    protected final void setBundle(Bundle bundle) {
        mBundle = bundle;
    }

    public Bundle getBundle() {
        return mBundle;
    }

    @Override
    public void startFragmentAndClearStack(BaseFragment fragment, Bundle bundle) {
        ((ISwitchFragment) getActivity()).startFragmentAndClearStack(fragment, bundle);
    }

    protected void showNetErrorToast() {
        Toast.makeText(mActivity, R.string.net_error, Toast.LENGTH_SHORT).show();
    }

}
